package com.mssh.login.service.impl;

import com.mssh.entity.table.SysResource;
import com.mssh.login.mapper.SysResourcesMapper;
import com.mssh.login.service.MenusService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 熳殊沙华
 * @Date: 2022/10/07/0:50
 * @Description: 菜单实现类
 */
@Service
public class MenusServiceImpl implements MenusService {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    private SysResourcesMapper resourcesMapper;

    /**
     * 根据用户id对应的资源
     * @param uid
     * @return
     */
    @Override
    public List<SysResource> findResourceByUserId(long uid) {
        List<SysResource> list = resourcesMapper.findResourceByUserId(uid);
        //返回的结果集
        List<SysResource> result = new ArrayList();
        //存储子节点
        List<SysResource> leafList = new ArrayList();
        //进行根节点/叶子节点分类
        while(list.size() > 0){
            SysResource menu = list.get(0);
            //判断是否为根节点
            if(menu.getIsSystemRoot() == 1){
                menu.setChild(new ArrayList());
                result.add(menu);
            }else{
                //展示存储在叶子节点数组中
                leafList.add(menu);
            }
            list.remove(0);
        }
        //在添加叶子节点
        while(leafList.size() > 0){
            SysResource leafMenu = leafList.get(0);
            for (int i = 0; i < result.size(); i++) {
                if(leafMenu.getParentId().equals(result.get(i).getMenuId())){
                    result.get(i).getChild().add(leafMenu);
                }
            }
            leafList.remove(0);
        }
        return result;
    }

}
